﻿using System;
using System.Threading;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;
using Windows.UI.StartScreen;

namespace Sumc.Client.ModernUI.BackgroundTasks
{
    public sealed class SecondTileUpdate : IBackgroundTask
    {
        private const int TileUpdateDelay = 420000;
        private readonly CancellationTokenSource cancellationToken = new CancellationTokenSource();

        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            taskInstance.Canceled += this.OnCanceled;
            var taskDeferral = taskInstance.GetDeferral();

            await Task.Delay(TileUpdateDelay, this.cancellationToken.Token);
            try
            {
                var tiles = await SecondaryTile.FindAllForPackageAsync().AsTask(cancellationToken.Token);
                if (tiles != null)
                {
                    foreach (SecondaryTile tile in tiles)
                    {
                        if (SecondaryTile.Exists(tile.TileId))
                        {
                            var tileUpdater = TileUpdateManager.CreateTileUpdaterForSecondaryTile(tile.TileId);
                            if (tileUpdater.Setting != NotificationSetting.Enabled)
                            {
                                continue;
                            }

                            var url = string.Concat("http://sofiatransport.apphb.com/api/Tiles?tileId=", tile.Arguments);
                            var uri = new Uri(url);
                            var xmlTile = await XmlDocument.LoadFromUriAsync(uri).AsTask<XmlDocument>(cancellationToken.Token);
                            tileUpdater.Update(new TileNotification(xmlTile));
                        }
                    }
                }
            }
            catch { }

            taskDeferral.Complete();
        }

        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            this.cancellationToken.Cancel();
        }
    }
}
